package common

import (
	"fmt"
	"strings"
	"sync/atomic"
	"time"
)

type Counter struct {
	name   string
	count  int64
	err    int64
	msg    string
	Async  bool
	ticker *time.Ticker
}

func NewCounter() *Counter {
	return &Counter{}
}

func (c *Counter) Init(name string) {
	c.name = name
	c.count = 0
	if c.Async {
		c.ticker = time.NewTicker(time.Millisecond * 100)
		go func() {
			for range c.ticker.C {
				c._print()
			}
		}()
	}
}

func (c *Counter) Add(count int) {
	atomic.AddInt64(&c.count, int64(count))
	if !c.Async {
		c._print()
	}
}

func (c *Counter) Err(count int, msg string) {
	atomic.AddInt64(&c.count, int64(count))
	atomic.AddInt64(&c.err, int64(count))
	c.msg = msg
	if !c.Async {
		c._print()
	}
}

func (c *Counter) Count() int64 {
	return c.count
}

func (c *Counter) _print() {
	fmt.Printf("\r%s，处理进度：%d，异常数：%d，备注：%s", c.name, c.count, c.err, c.msg)
}

func (c *Counter) Finish(format string, param ...interface{}) {
	if c.ticker != nil {
		c.ticker.Stop()
	}
	if format == "" {
		format = "\r%s，处理完成：%d\n"
		param = []interface{}{c.name, c.count}
	} else {
		if !strings.HasPrefix(format, "\r") {
			format = "\r" + format
		}
		if !strings.HasSuffix(format, "\n") {
			format = format + "\n"
		}
	}
	fmt.Printf(format, param...)
}
